package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyCatalogMapper;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public StrategyDetail get(Long id) {
        //1:查询文章的基本信息
        StrategyDetail strategyDetail = strategyDetailMapper.selectByPrimaryKey(id);
        //2:查询文章的内容
        StrategyContent strategyContent = contentMapper.selectByPrimaryKey(id);
        strategyDetail.setStrategyContent(strategyContent);
        return strategyDetail;
    }

    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public String getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id).getContent();
    }

    public void saveOrUpdate(StrategyDetail entity) {
        //自动生成序号
        if (entity.getSequence() == null) {
            //用户没有填序号,可以自动生成
            //1:先查询当前攻略中最大序号
            Integer sequence = strategyDetailMapper
                    .selectMaxSequenceByCatalogId(entity.getCatalog().getId());
            //2:判断是否为null,默认给以1,不为null则+1再设置进去
            if (sequence == null) {
                sequence = 0;
            }
            entity.setSequence(sequence + 1);
        }
        //设置发布时间
        if (entity.getState() == StrategyDetail.STATE_RELEASE) {
            entity.setReleaseTime(new Date());
        }
        //文章内容的主键关联
        StrategyContent strategyContent = entity.getStrategyContent();
        if (entity.getId() == null) {
            //设置创建时间
            entity.setCreateTime(new Date());
            strategyDetailMapper.insert(entity);
            strategyContent.setId(entity.getId());
            contentMapper.insert(strategyContent);
        } else {
            strategyDetailMapper.updateByPrimaryKey(entity);
            strategyContent.setId(entity.getId());
            contentMapper.updateByPrimaryKey(strategyContent);
        }
    }
}
